<?php
	/**
	 * User validator via database.
	 * @author IMP
	 */
	
	class DatabaseUserLogin extends UserLogin implements UserLoginValidator {
		private $table, $groups = array(), $db;
		
		public function __construct(array &$session, Database $db, $table, array $groups = array()){
			$this->table = $db->getPrefix() . $table;
			$this->groups = $groups;
			$this->db = $db;
			
			parent::__construct($session, $this);
		}
		
		public function validate($username, $password){
			$pw = md5($password);
			$q = $this->db->query('SELECT * FROM ' . $this->table . ' WHERE loginName = "' . $this->db->escape($username) . '" AND loginPassword = "' . $pw . '";');
			
			if($q->getRowCount() > 0){
				$data = $q->fetchAssoc();
				$this->cache[$data['loginID']] = $data; 
				return new DatabaseUser($this, $data['loginID']);
			}else return null;
		}
		
		private $nameCache = array();
		
		public function getProperty(DatabaseUser $u, $property){
			if(!empty($this->cache[$u->getID()][$property])){
				return $this->cache[$u->getID()][$property];
			}else{
				$q = $this->db->query('SELECT * FROM ' . $this->table . ' WHERE loginID = ' . $u->getID() . ';');
				if($q->getRowCount() > 0){
					$data = $q->fetchAssoc();
					$this->cache[$u->getID()] = $data; 
					
					if(!empty($this->cache[$u->getID()][$property])){
						return $this->cache[$u->getID()][$property];
					}else{
						throw new DatabaseException('No property ' . $property . ' for ID ' . $u->getID() . '.');
					}
				}else{
					throw new DatabaseException('No user entry for ID ' . $u->getID() . '.');
				}
			}
		}
	}
?>